#include "../_Module/CKRuleManage.h"
#include "CKMsg.h"
#include "CKThread.h"
#include "CKMsgQueue.h"
#include "CKThreadPool.h"



namespace K_Engine
{
	CKThread::CKThread(
			popworkCallBack _popworkcallback, 
			void* _threadpool,
			resultCallBack _resultcallback, 
			void* _pushreslut) :
		m_popworkcallback(_popworkcallback),
		m_resultcallback(_resultcallback),
		m_pthreadpool(_threadpool),
		m_pushresult(_pushreslut),
		m_isWork(false),
		m_isAlive(true)
	{
		m_pthread = new std::thread(&CKThread::run, this);
	}
	
	
	CKThread::~CKThread()
	{
		m_pthread->join();
		delete m_pthread;
	}
	
	
	bool CKThread::bGetIsWork()
	{
		return m_isWork;
	}
	
	
	void CKThread::ChangeIsAlive(bool _bisalive)
	{
		m_isAlive = _bisalive;
	}
	
	
	void CKThread::run()
	{
		while(m_isAlive)
		{
			std::string msg = m_popworkcallback(m_pthreadpool);
			if(msg.empty())continue;
			m_isWork = true;
			CKMsg ckmsg;
			if(ckmsg.ParserMSG(msg))
			{//解析成功
				if(CKMsg::Work == ckmsg.GetType())
				{
					CKRule* workrule = CKRuleManage::GetInstance()->
						GetRuleObject(ckmsg.GetRuleName());
					if(NULL == workrule)
					{
						std::string strtemp = "消息对应的规则";
						strtemp += ckmsg.GetRuleName() + "为空";
						ckmsg.SetRuleName(strtemp);
						ckmsg.SetType(CKMsg::Error);
						m_resultcallback(m_pushresult, ckmsg.FormatMSG());
					}
					else
					{
						void *workobj = workrule->GetObject(ckmsg.GetParams());
						std::string result = workrule->DoingWork(workobj);
						workrule->DeleteObject(workobj);
						workobj = NULL;
						ckmsg.SetType(CKMsg::Return);
						if(result.empty())
						{
							ckmsg.SetRuleName("");
							m_resultcallback(m_pushresult, ckmsg.FormatMSG());
						}
						else if("ERROR" == result)
						{
							ckmsg.SetType(CKMsg::Error);
							m_resultcallback(m_pushresult, ckmsg.FormatMSG());
						}
						else
						{
							std::vector<std::string> vResult;
							CKMsg::FormatResultMSG(result, vResult);
							for(int i = 0; i < vResult.size(); i++)
							{
								ckmsg.SetParams(vResult[i]);
								m_resultcallback(m_pushresult, ckmsg.FormatMSG());
							}	
						}
						
					}
				}
				else
				{//非工作模块
					ckmsg.SetRuleName("该消息不是工作消息");
					ckmsg.SetType(CKMsg::Error);
					m_resultcallback(m_pushresult, ckmsg.FormatMSG());
				}
			}
			else
			{//解析失败
				ckmsg.SetRuleName("消息解析失败");
				ckmsg.SetType(CKMsg::Error);
				m_resultcallback(m_pushresult, ckmsg.FormatMSG());
			}			
			
			m_isWork = false;
		}
	}
}
